package com.example.mplayer.viewmodels

import android.app.Application
import android.os.Build
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.example.mplayer.data.AppDatabase
import com.example.mplayer.data.CardKey
import com.example.mplayer.data.Course
import com.example.mplayer.data.Chapter
import com.example.mplayer.data.Video
import com.example.mplayer.network.EncryptedKeyRequest
import com.example.mplayer.network.CourseResponse
import com.example.mplayer.network.ChapterResponse
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import android.provider.Settings
import androidx.annotation.RequiresApi
import com.example.mplayer.data.ChapterWithVideos
import com.example.mplayer.network.NetworkModule
import com.example.mplayer.utils.EncryptionUtils
import kotlinx.coroutines.flow.StateFlow
import android.util.Log

class CardKeyViewModel(application: Application) : AndroidViewModel(application) {
    private val cardKeyDao = AppDatabase.getDatabase(application).cardKeyDao()
    private val courseDao = AppDatabase.getDatabase(application).courseDao()
    private val courseService = NetworkModule.courseService

    private val _courseLoadingState = MutableStateFlow<CourseLoadingState>(CourseLoadingState.Initial)
    val courseLoadingState: StateFlow<CourseLoadingState> = _courseLoadingState.asStateFlow()

    val allCardKeys: Flow<List<CardKey>> = cardKeyDao.getAllCardKeys()

    fun addCardKey(key: String, note: String = "") {
        viewModelScope.launch {
            val cardKey = CardKey(key = key, note = note)
            cardKeyDao.insert(cardKey)
            fetchCourse(key)
        }
    }

    fun updateCardKey(cardKey: CardKey) {
        viewModelScope.launch {
            cardKeyDao.update(cardKey)
            fetchCourse(cardKey.key)
        }
    }

    fun deleteCardKey(cardKey: CardKey) {
        viewModelScope.launch {
            cardKeyDao.delete(cardKey)
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private suspend fun fetchCourse(key: String) {
        _courseLoadingState.value = CourseLoadingState.Loading
        try {
            val deviceId = Settings.Secure.getString(
                getApplication<Application>().contentResolver,
                Settings.Secure.ANDROID_ID
            )
            val encryptedData = EncryptionUtils.encryptKey(key)
            val request = EncryptedKeyRequest(deviceId, encryptedData)
            
            val response = courseService.getCourse(request)
            saveCourseToDatabase(response)
            
            _courseLoadingState.value = CourseLoadingState.Success
        } catch (e: Exception) {
            _courseLoadingState.value = CourseLoadingState.Error(e.message ?: "Unknown error")
        }
    }

    private suspend fun saveCourseToDatabase(courseResponse: CourseResponse) {
        try {
            val course = Course(
                id = courseResponse.id,
                title = courseResponse.title
            )
            
            val chapters = mutableListOf<Chapter>()
            val videos = mutableListOf<Video>()
            
            fun processChapter(chapter: ChapterResponse, parentId: String?) {
                Log.d("Database", """
                    Processing chapter: ${chapter.id}
                    title: ${chapter.title}
                    parentId: $parentId
                    courseId: ${course.id}
                """.trimIndent())
                
                chapters.add(Chapter(
                    id = chapter.id,
                    courseId = course.id,
                    parentId = parentId,
                    title = chapter.title
                ))
                
                chapter.videos.forEach { video ->
                    videos.add(Video(
                        id = video.id,
                        chapterId = chapter.id,
                        title = video.title,
                        url = video.url
                    ))
                }
                
                chapter.sub_chapters?.forEach { subChapter ->
                    processChapter(subChapter, chapter.id)
                }
            }
            
            courseResponse.chapters.forEach { chapter ->
                processChapter(chapter, null)
            }
            
            Log.d("Database", """
                Saving course: ${course.id}
                chapters: ${chapters.map { it.id to it.parentId }}
                videos: ${videos.size} items
            """.trimIndent())
            
            courseDao.insertFullCourse(course, chapters, videos)
            Log.d("Database", "Save completed successfully")
        } catch (e: Exception) {
            Log.e("Database", "Error saving course", e)
            throw e
        }
    }

    suspend fun getChapterHierarchy(parentChapterId: String?): List<ChapterWithVideos> {
        return courseDao.getSubChapters(parentChapterId)
    }
}

sealed class CourseLoadingState {
    object Initial : CourseLoadingState()
    object Loading : CourseLoadingState()
    object Success : CourseLoadingState()
    data class Error(val message: String) : CourseLoadingState()
}